package com.sugeun.timer;

import java.io.IOException;

import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.Vibrator;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;

public class TimerService extends Service {
	private static final String TAG = "TimerService";
	private MediaPlayer mMediaPlayer;
	private AudioManager mAudioManager;
	private Vibrator mVibrator;
	private String mTone;
	private ContentResolver mResolver;
	private static final int VIB_WAIT = 200, VIB_KEEP = 800;
	private final long[] vibratePatterns = new long[]{VIB_WAIT, VIB_KEEP};
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		Log.e(TAG,"============onCreate============== ");	
		mMediaPlayer = new MediaPlayer();		
		mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		mVibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
		
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		//Log.e(TAG,"intent11111111111111111 : "+intent);
		if (intent == null) {
            stopSelf();
            return START_NOT_STICKY;
        }
		Boolean mVibration = (boolean)intent.getBooleanExtra("Vibration", true);
		String mRingtone = (String)intent.getStringExtra("Ringtone");
		Log.e(TAG,"mRingtone : "+mRingtone);
		if(mRingtone == null) {
			stopSelf();
			return START_NOT_STICKY;
		}
		
		wakeAlarm(mVibration, mRingtone);
		
		return START_STICKY;
	}
	public void wakeAlarm(boolean isVib, String ringtone) {
		if(isVib) {
			Log.e(TAG,"isVib : "+isVib);
			mVibrator.vibrate(vibratePatterns, 0);
		}
		
		try {		
	            
	            int status = 0;
	            String path = null;
	           
	           
	            	mMediaPlayer.setDataSource(this, Uri.parse(ringtone));
	            
	            if ( mMediaPlayer != null ) {
	            	mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
			    	mMediaPlayer.setLooping(true);
			    	mMediaPlayer.setVolume(mAudioManager.getStreamVolume(AudioManager.STREAM_RING), mAudioManager.getStreamVolume(AudioManager.STREAM_RING));
					mMediaPlayer.prepare();
	            }
			
		}
		catch (IllegalArgumentException e1) { 
			e1.printStackTrace();
		} 
		catch (SecurityException e1) {
			e1.printStackTrace();
		}
		catch (IllegalStateException e1) {
			e1.printStackTrace();
		}
		catch (IOException e1) {
			e1.printStackTrace();
			//defaultTone();
		}
		
		if ( mMediaPlayer != null )
			mMediaPlayer.start();
	}
	
	 private static final String[] INTERNAL_COLUMNS = new String[] {
 		BaseColumns._ID,
 		MediaStore.MediaColumns.TITLE,
 		"\"" + MediaStore.Audio.Media.INTERNAL_CONTENT_URI + "\"",
 		MediaStore.Audio.AudioColumns.TITLE_KEY
	 };
	 
	/*private void defaultTone() {
    	Uri alert = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
	    if (alert == null) {
	    	mTone = "default";
        	return; 
	    } else { 
	    	int i = 1;
            boolean tag = false;
            String defaulttone = "";
            
            mResolver = this.getContentResolver();
	    	Cursor cur = mResolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS,
    						               			null,  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);            
    	 	try {
    	 		if ( cur != null && cur.moveToFirst() ) {
    	 			do {
        	 			// Get the field values     
        	            Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
        	            if (uri1.toString().equalsIgnoreCase(alert.toString())) {
        	            	mTone =	uri1.toString();
        	            	TimerMain.saveTonePreferences(uri1.toString());
        	             	
        	            	tag = true;
    	    	            break;
        	            }
        	              
        	            if (i == 4) {
        	            	defaulttone = uri1.toString();
        	            }
        	            i++;
        	 		} while (cur.moveToNext());
        	 	}
    	 	} catch (Exception e) {
    	 		e.printStackTrace();
    	 	} finally {
    	 		if (cur != null)
    	 			cur.close();
    	 	}
    	 	        
			if (tag == false) { 
				mTone =	defaulttone;
				TimerMain.saveTonePreferences(defaulttone);
			}
	    }
	    
	    try {
	    	if ( mMediaPlayer != null ) {
	    		mMediaPlayer.setDataSource(this, Uri.parse(mTone)) ;
				mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
		    	mMediaPlayer.setLooping(true);
		    	mMediaPlayer.setVolume(mAudioManager.getStreamVolume(AudioManager.STREAM_RING), mAudioManager.getStreamVolume(AudioManager.STREAM_RING));
				mMediaPlayer.prepare();
				mMediaPlayer.start();
	    	}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/
	
	@Override
	public void onDestroy() {
		
		releaseAlarm();
	
	}
	private void releaseAlarm() {
		if(mVibrator != null) {
			mVibrator.cancel();
		}
		if (mMediaPlayer != null) {
			mMediaPlayer.stop();
			mMediaPlayer.release();
			mMediaPlayer = null;
          
		}
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
